﻿using Redis;
using SuperiorCommon;
using SuperiorShopBussinessService;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;
using WxPayAPIMobileShopCode.Common.Helpers;
using SuperiorModel;

namespace SuperiorShopkeeper.Controllers
{
    public class RechargeController : BaseController
    {
        private readonly IHomeService _IHomeService;
        private readonly IShopService _IShopService;

        public RechargeController(IHomeService IHomeService, IShopService IShopService)
        {
            _IHomeService = IHomeService;
            _IShopService = IShopService;
        }
        protected override void Dispose(bool disposin)
        {
            this._IHomeService.Dispose();
            this._IShopService.Dispose();
            base.Dispose(disposin);
        }
        // GET: Recharge
        public ActionResult Index()
        {
            return View();
        }

        [CheckLoginFitler]
        public ActionResult Success()
        {
            return View();
        }
        /// <summary>
        /// 轮询请求当前充值订单状态
        /// </summary>
        /// <returns></returns>
        [AjaxOnly]
        public JsonResult GetRechargeOrderStatus()
        {
            var orderid = Session["CURRENT_ORDERID"];
            if (orderid == null)
                return Error("");
            var res = _IHomeService.GetRechargeOrderStatus(Convert.ToInt32(orderid));
            return Success(res);
        }

        private static object LockData = new object();

        [HttpPost]
        public ActionResult WxPayBack() {
            //接收从微信后台POST过来的数据
            System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;
            int count = 0;
            byte[] buffer = new byte[1024];
            StringBuilder builder = new StringBuilder();
            while ((count = s.Read(buffer, 0, 1024)) > 0)
            {
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();
            LogManger.Instance.WriteLog("微信回调返回数据：" + builder.ToString());
            //转换数据格式并验证签名
            WxPayData data = new WxPayData();
            try
            {
                data.FromXml(builder.ToString());
                //2015-06-29 错误时没有签名
                if (data.IsSet("return_code") && data.GetValue("return_code").ToString() == "SUCCESS" && data.IsSet("sign") && data.GetValue("sign").ToString() != "")
                {
                    string appid = data.GetValue("appid").ToString();
                    string paykey = ConfigSettings.Instance.PaySecret;
                    string userid = data.GetValue("attach").ToString();
                    LogManger.Instance.WriteLog("带回来的USERID："+userid+"  appid="+appid+"-----paykey="+paykey);
                    if (appid != null)
                    {
                        //获取接收到的签名
                        string return_sign = data.GetValue("sign").ToString();
                        //在本地计算新的签名
                        string cal_sign = data.MakeSign(paykey);
                        if (cal_sign == return_sign)
                        {
                            //更新订单状态
                            string out_trade_no = data.GetValue("out_trade_no").ToString();
                            //重复调用验证
                            lock (LockData)
                            {

                                if (RedisManager.Get<string>(out_trade_no) != null)
                                {
                                    LogManger.Instance.WriteLog("微信支付回调发生了频繁重复调用！订单号" + out_trade_no);
                                    return null;
                                }
                                else
                                {
                                    //将当前订单号写入缓存
                                    RedisManager.Set(out_trade_no, out_trade_no, DateTime.Now.AddMinutes(15));
                                }
                            }
                            string transaction_id = data.GetValue("transaction_id").ToString();
                            string result_code = data.GetValue("result_code").ToString();
                            string err_code = data.IsSet("err_code") ? data.GetValue("err_code").ToString() : string.Empty;
                            string time_end = data.GetValue("time_end").ToString();
                            float total_fee = 0; Int64 paytime; int status = 0;
                            float.TryParse(data.GetValue("total_fee").ToString(), out total_fee);
                            Int64.TryParse(time_end, out paytime);
                            if (result_code == "SUCCESS")
                            {
                                status = 1;
                            }
                            else if (result_code == "FAIL")
                            {
                                status = 2;
                            }
                            else
                            {
                                LogManger.Instance.WriteLog("微信回调业务结果错误返回信息：" + builder.ToString() + ";业务结果：" + result_code);
                            }
                            LogManger.Instance.WriteLog("out_trade_no：" + out_trade_no + ";status" + status + "total_fee=" + (total_fee / 100));
                            if (status == 1 || status == 2)
                            {
                                string msg = "";
                                var ret = _IHomeService.WxRechargeCall(out_trade_no, transaction_id, status, out msg);
                                if (ret == 1)
                                {
                                    //更新用户session
                                    
                                    //控制redis
                                    //清楚该商户下的所有店铺信息redis
                                    var listIds = _IShopService.GetShopAppIdsByShopAdminId(SecretClass.DecryptQueryString(userid).ToInt());
                                    if (listIds.Count > 0)
                                    {
                                        var _keys = new List<string>();
                                        foreach (var id in listIds)
                                        {
                                            _keys.Add("GetShopAppModel_" + id);
                                        }
                                        RedisManager.RemoveList(_keys);
                                    }
                                }
                                   

                                
                                LogManger.Instance.WriteLog("微信回调更改状态返回" + ret);
                            }
                            WxPayData res = new WxPayData();
                            res.SetValue("return_code", "SUCCESS");
                            res.SetValue("return_msg", "OK");
                            return Content(res.ToXml());
                            
                        }
                        else
                        {
                            LogManger.Instance.WriteLog("微信回调签名认证失败返回信息：" + builder.ToString() + ";接收到签名：" + return_sign + ";本地签名：" + cal_sign);
                            WxPayData res = new WxPayData();
                            res.SetValue("return_code", "FAIL");
                            res.SetValue("return_msg", "签名失败");
                            return Content(res.ToXml());
                        }
                    }
                    else
                    {
                        LogManger.Instance.WriteLog("微信回调获取商户信息失败返回信息：" + builder.ToString());
                        WxPayData res = new WxPayData();
                        res.SetValue("return_code", "FAIL");
                        res.SetValue("return_msg", "商户不存在");
                        return Content(res.ToXml());
                    }
                }
                else
                {
                    LogManger.Instance.WriteLog("微信回调返回失败返回信息：" + builder.ToString());
                    WxPayData res = new WxPayData();
                    res.SetValue("return_code", "FAIL");
                    res.SetValue("return_msg", "参数格式校验错误");
                    return Content(res.ToXml());
                }
            }
            catch (Exception ex)
            {
                LogManger.Instance.WriteLog("微信回调异常，返回内容：" + builder.ToString() + ";异常信息：" + ex.Message + ";异常堆栈：" + ex.StackTrace);
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "回调数据异常");
                return Content(res.ToXml());
            }
            finally
            {

            }
        }
    }
}